<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
  import echarts from 'echarts'

  require('echarts/theme/macarons') // echarts theme
  import {debounce} from '@/utils'

  const animationDuration = 1000

  export default {
    name: 'profit-chart',
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '300px'
      },
      xData: Array,
      yData: Array,
    },
    data() {
      return {
        chart: null
      }
    },
    watch: {
      yData() {
        this.renderChart();
      }
    },
    mounted() {
      this.initChart()
      this.__resizeHanlder = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHanlder)
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      window.removeEventListener('resize', this.__resizeHanlder)
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')
        this.renderChart()
      },
      renderChart() {
        // filter(info => (info.value !== consts.ALL && info.value != consts.PY))
        const series = _(consts.PLATFORM_TYPE).map((type) => {
          let ydata = _.find(this.yData, {title: type.title});
          return {
            name: type.title,
            type: 'line',
            // stack: '总量',
            data: (ydata && ydata.value) || [],
            animationDuration
          }
        }).value();

        this.chart.setOption({
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            // data: _(consts.PLATFORM_TYPE).filter(info => (info.value !== consts.ALL && info.value != consts.PY)).map('title').value(),
            data: _(consts.PLATFORM_TYPE).map('title').value(),
            x: 'right',
            y: -5,
            padding: 10,
            // data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
          },
          calculable: true,
          dataZoom: {
            show: true,
            realtime: true,
            start: 0,
            end: 100
          },
          grid: {
            top: 20,
            left: '2%',
            right: '2%',
            bottom: '3%',
            containLabel: true
          },

          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              data: this.xData,
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: series,
        })
      }
    }
  }
</script>
